<?php

namespace july\julyadmin\builder\table;

use july\julyadmin\common\logic\AdminRoleLogic;

/**
 * 表格工具栏
 * @author July
 */
class Toolbar
{
    //所属表格id
    protected $tableId = '';
    //工具栏html
    protected $html = '';
    //工具栏script
    protected $script = '';
    //类型toolbar,tablerow
    protected $type = '';
    //父对象
    protected $parent;
    //表格类型
    protected $tableType = 'table';
    //当前模块
    protected $module = '';
    //主键字段
    protected $pk = '';

    public function __construct($parent, $type, $pk = '')
    {
        $this->parent = $parent;
        $this->type   = $type;
        $this->pk     = $pk;

        $this->module = input('get.module', app('http')->getName());
    }

    /**
     * 设置表格类型
     * @param string $type 表格类型table,treeTable
     * @return  this
     */
    public function tableType($type = 'table')
    {
        $this->tableType = $type;
        return $this;
    }

    /**
     * @param boolean $show           是否显示添加按钮
     * @param string  $title          按钮title
     * @param string  $window_width   窗口宽度
     * @param string  $window_height  窗口高度
     * @param boolean $is_parent_open 是否从父窗口打开
     */
    public function addBtn($show = true, $title = null, $window_width = '90%', $window_height = '90%', $is_parent_open = false)
    {
        if ($this->type == 'tablerow') {
            $icon_span = '';
        } else {
            $icon_span = '<span class="mdi mdi-plus" aria-hidden="true"></span>';
        }
        if ($show == true) {
            if (!AdminRoleLogic::isHaveButtonPermission($this->module, request()->controller(), 'add')) {
                return $this;
            }
            if ($title === null) {
                $title = $this->parent->addText;
            }
            $href = url(request()->controller() . "/add", input('get.'));

            $parent = $is_parent_open ? 'parent.' : '';

            if ($this->type == 'tablerow') {
                $btn_cls = 'layui-btn layui-btn-xs';
            } else {
                $btn_cls = 'btn btn-sm btn-success';
            }

            $html = <<<EOT

            {{# if(!d.hasOwnProperty('__add_hidden__') || d.__add_hidden__==false){}}
                <button row-id="{{d.{$this->pk}}}" class="julyadmin_{$this->tableId}_{$this->type}_btn_add {$btn_cls}" onclick="{$this->tableId}_{$this->type}_add_function(this)">
                    {$icon_span}{$title}
                </button>
            {{# }}}

EOT;
            $this->script .= <<<EOT

            <script>
                function {$this->tableId}_{$this->type}_add_function(that){
                    var url = '{$href}';
                    var ids = [];
                    if('{$this->type}'=='toolbar'){
                        var data = layui.{$this->tableType}.checkStatus('{$this->tableId}').data;
                        if(data.length>1){
                            layer.msg('不能同时选择多项！',{
                                icon:5,
                                time:2000,
                                shade:[0.6,'#000',false]
                            });
                            return false;
                        }else if(data.length==1){
                            ids.push(data[0]['{$this->pk}']);
                        }
                    }else{
                        ids.push($(that).attr('row-id'));
                    }
                    if(ids.length>0){
                        if(url.indexOf("?")>-1){
                            url = url+'&{$this->pk}='+ids.join(",");
                        }else{
                            url = url+'?{$this->pk}='+ids.join(",");
                        }
                    }
                    {$parent}layer.open({
                        type: 2,
                        title: '{$title}',
                        shadeClose: false,
                        shade:0.5,
                        maxmin: true, //开启最大化最小化按钮
                        area: ['{$window_width}', '{$window_height}'],
                        content: url
                    });
                }
           </script>

EOT;
            $this->html .= $html;
        }
        return $this;
    }

    /**
     * @param boolean $show           是否显示编辑按钮
     * @param string  $title          按钮title
     * @param string  $window_width   窗口宽度
     * @param string  $window_height  窗口高度
     * @param boolean $is_parent_open 是否从父窗口打开
     */
    public function editBtn($show = true, $title = null, $window_width = '90%', $window_height = '90%', $is_parent_open = false)
    {
        if ($this->type == 'tablerow') {
            $icon_span = '';
        } else {
            $icon_span = '<span class="mdi mdi-note-check-outline" aria-hidden="true"></span>';
        }
        if ($show == true) {
            if (!AdminRoleLogic::isHaveButtonPermission($this->module, request()->controller(), 'edit')) {
                return $this;
            }
            if ($title === null) {
                $title = $this->parent->editText;
            }
            $parent = $is_parent_open ? 'parent.' : '';
            $href   = url(request()->controller() . "/edit", input('get.'));

            $noEditPrimarykeys = json_encode($this->parent->noEditPrimarykeys);
            if ($this->type == 'tablerow') {
                $btn_cls = 'layui-btn layui-btn-xs layui-bg-blue';
            } else {
                $btn_cls = 'btn btn-sm btn-primary';
            }
            $html = <<<EOT
            {{# if(!d.hasOwnProperty('__edit_hidden__') || d.__edit_hidden__==false){}}
                <button row-id="{{d.{$this->pk}}}" type="button" class="julyadmin_{$this->tableId}_{$this->type}_btn_edit {$btn_cls}" onclick="{$this->tableId}_{$this->type}_edit_function(this)">
                    {$icon_span}{$title}
                </button>
            {{# }}}

EOT;
            $this->script .= <<<EOT

            <script>
                function {$this->tableId}_{$this->type}_edit_function(that){
                    var url = '{$href}';
                    var ids = [];
                    if('{$this->type}'=='toolbar'){
                        var data = layui.{$this->tableType}.checkStatus('{$this->tableId}').data;
                        if(data.length==0){
                            layer.msg('为选择要操作的项！',{
                                icon:5,
                                time:2000,
                                shade:[0.6,'#000',false]
                            });
                            return false;
                        }else if(data.length>1){
                            layer.msg('不能同时编辑多项！',{
                                icon:5,
                                time:2000,
                                shade:[0.6,'#000',false]
                            });
                            return false;
                        }else{
                            ids.push(data[0]['{$this->pk}']);
                        }
                    }else{
                        ids.push($(that).attr('row-id'));

                    }
                    if(ids.length>0){
                        if(url.indexOf("?")>-1){
                            url = url+'&{$this->pk}='+ids.join(",");
                        }else{
                            url = url+'?{$this->pk}='+ids.join(",");
                        }
                    }

                    var noEditPrimarykeys = {$noEditPrimarykeys};
                    var is_exit = false;
                    if(noEditPrimarykeys.length>0){
                        ids.map(item=>{
                            if(noEditPrimarykeys.includes(item) || noEditPrimarykeys.includes(item.toString())){
                                layer.msg('当前行不允许编辑！',{
                                    icon:5,
                                    time:2000,
                                    shade:[0.6,'#000',false]
                                });
                                is_exit = true;
                            }
                        });
                    }

                    if(!is_exit){
                        {$parent}layer.open({
                            type: 2,
                            title: '{$title}',
                            shadeClose: false,
                            shade:0.5,
                            maxmin: true, //开启最大化最小化按钮
                            area: ['{$window_width}', '{$window_height}'],
                            content: url
                        });
                    }
                }
           </script>

EOT;
            $this->html .= $html;
        }
        return $this;
    }

    /**
     * 详情按钮
     * @param boolean $show           是否显示详情按钮
     * @param string  $title          按钮title
     * @param string  $window_width   窗口宽度
     * @param string  $window_height  窗口高度
     * @param boolean $is_parent_open 是否从父窗口打开
     */
    public function viewBtn($show = true, $title = null, $window_width = '90%', $window_height = '90%', $is_parent_open = false)
    {
        if ($this->type == 'tablerow') {
            $icon_span = '';
        } else {
            $icon_span = '<span class="mdi mdi-view-dashboard-edit-outline" aria-hidden="true"></span>';
        }

        if ($show == true) {
            if (!AdminRoleLogic::isHaveButtonPermission($this->module, request()->controller(), 'view')) {
                return $this;
            }
            if ($title === null) {
                $title = $this->parent->viewText;
            }
            $parent            = $is_parent_open ? 'parent.' : '';
            $href              = url(request()->controller() . "/view", input('get.'));
            $noEditPrimarykeys = json_encode($this->parent->noEditPrimarykeys);

            if ($this->type == 'tablerow') {
                $btn_cls = 'layui-btn layui-btn-xs layui-bg-purple';
            } else {
                $btn_cls = 'btn btn-sm btn btn-info';
            }
            $html = <<<EOT

                {{# if(!d.hasOwnProperty('__view_hidden__') || d.__view_hidden__==false){}}
                    <button row-id="{{d.{$this->pk}}}" type="button" class="julyadmin_{$this->tableId}_{$this->type}_btn_view {$btn_cls}" onclick="{$this->tableId}_{$this->type}_view_function(this)">
                        {$icon_span}{$title}
                    </button>
                {{# }}}

EOT;
            $this->script .= <<<EOT
            <script>
                function {$this->tableId}_{$this->type}_view_function(that){
                    var url = '{$href}';
                    var ids = [];
                    if('{$this->type}'=='toolbar'){
                        var data = layui.{$this->tableType}.checkStatus('{$this->tableId}').data;
                        if(data.length==0){
                            layer.msg('为选择要查看的项！',{
                                icon:5,
                                time:2000,
                                shade:[0.6,'#000',false]
                            });
                            return false;
                        }else if(data.length>1){
                            layer.msg('不能同时查看多项！',{
                                icon:5,
                                time:2000,
                                shade:[0.6,'#000',false]
                            });
                            return false;
                        }else{
                            ids.push(data[0]['{$this->pk}']);
                        }
                    }else{
                        ids.push($(that).attr('row-id'));
                    }
                    if(ids.length>0){
                        if(url.indexOf("?")>-1){
                            url = url+'&{$this->pk}='+ids.join(",");
                        }else{
                            url = url+'?{$this->pk}='+ids.join(",");
                        }
                    }

                    {$parent}layer.open({
                        type: 2,
                        title: '{$title}',
                        shadeClose: false,
                        shade:0.5,
                        maxmin: true, //开启最大化最小化按钮
                        area: ['{$window_width}', '{$window_height}'],
                        content: url
                    });
                }
           </script>
EOT;
            $this->html .= $html;
        }
        return $this;
    }

    /**
     * @param boolean $show           是否显示禁用开启按钮
     * @param string  $title          按钮文字
     */
    public function disabledBtn($show = true, $title = null)
    {
        if ($this->type == 'tablerow') {
            $icon_span = '';
        } else {
            $icon_span = '<span class="mdi mdi-block-helper" aria-hidden="true"></span>';
        }
        if ($show == true) {
            if (!AdminRoleLogic::isHaveButtonPermission($this->module, request()->controller(), 'disabled')) {
                return $this;
            }
            if ($title === null) {
                $title = $this->parent->disabledText;
            }
            $href                  = url(request()->controller() . "/disabled", input('get.'));
            $noDisabledPrimarykeys = json_encode($this->parent->noDisabledPrimarykeys);

            if ($this->type == 'tablerow') {
                $btn_cls = 'layui-btn layui-btn-xs layui-bg-black';
            } else {
                $btn_cls = 'btn btn-sm btn-warning';
            }

            $html = <<<EOT

            {{# if(!d.hasOwnProperty('__disabled_hidden__') || d.__disabled_hidden__==false){}}
                <button row-id="{{d.{$this->pk}}}" type="button" class="julyadmin_{$this->tableId}_{$this->type}_btn_disabled {$btn_cls}" onclick="{$this->tableId}_{$this->type}_disabled_function(this)">
                    {$icon_span}{$title}
                </button>
            {{# }}}

EOT;
            $this->script .= <<<EOT
            <script>
                function {$this->tableId}_{$this->type}_disabled_function(that){
                    var ids = [];
                    if('{$this->type}'=='toolbar'){
                        var data = layui.{$this->tableType}.checkStatus('{$this->tableId}').data;
                        data.map(item=>{
                            ids.push(item['{$this->pk}'])
                        });
                    }else{
                        ids.push($(that).attr('row-id'));
                    }
                    if(ids.length==0){
                        layer.msg('请选择要操作的项！',{
                            icon:5,
                            time:2000,
                            shade:[0.6,'#000',false]
                        });
                        return false;
                    }

                    var noDisabledPrimarykeys = {$noDisabledPrimarykeys};
                    var is_exit = false;
                    if(noDisabledPrimarykeys.length>0){
                        ids.map(item=>{
                            if(noDisabledPrimarykeys.includes(item) || noDisabledPrimarykeys.includes(item.toString())){
                                layer.msg('当前行不允许操作！',{
                                    icon:5,
                                    time:2000,
                                    shade:[0.6,'#000',false]
                                });
                                is_exit = true;
                            }
                        });
                    }

                    if(!is_exit){
                        layer.confirm('是否确认执行{$title}操作？', {
                            btn: ['确定', '取消'],
                            icon:'doubt'
                        }, function(index, layero){
                            //确认按钮回调
                            layer.close(index);
                            window.loading  = layer.load(2, { shade:  [0.2, '#000'] });
                            $.post('{$href}',{{$this->pk}:ids.join(",")},function(res){
                                layer.close(window.loading);
                                if(res.code==1){
                                    layer.msg(res.msg,{
                                        icon:6,
                                        time:2000,
                                        shade:[0.6,'#000',false]
                                    });
                                    layui.{$this->tableType}.reloadData('{$this->tableId}');
                                }else{
                                    layer.msg(res.hasOwnProperty('msg') && res.msg?res.msg:'操作失败！',{
                                        icon:5,
                                        time:2000,
                                        shade:[0.6,'#000',false]
                                    });
                                }
                            });
                        });
                    }

                }
           </script>
EOT;
            $this->html .= $html;
        }
        return $this;
    }

    /**
     * @param boolean $show   是否显示删除按钮
     * @param string  $title  按钮文字
     */
    public function deleteBtn($show = true, $title = null)
    {
        if ($this->type == 'tablerow') {
            $icon_span = '';
        } else {
            $icon_span = '<span class="mdi mdi-window-close" aria-hidden="true"></span>';
        }
        if ($show == true) {
            if (!AdminRoleLogic::isHaveButtonPermission($this->module, request()->controller(), 'delete')) {
                return $this;
            }
            if ($title === null) {
                $title = $this->parent->deleteText;
            }
            $href                = url(request()->controller() . "/delete", input('get.'));
            $noDeletePrimarykeys = json_encode($this->parent->noDeletePrimarykeys);

            if ($this->type == 'tablerow') {
                $btn_cls = 'layui-btn layui-btn-xs layui-bg-red';
            } else {
                $btn_cls = 'btn btn-sm btn-danger';
            }

            $html = <<<EOT

            {{# if(!d.hasOwnProperty('__delete_hidden__') || d.__delete_hidden__==false){}}
                <button row-id="{{d.{$this->pk}}}" type="button" class="julyadmin_{$this->tableId}_{$this->type}_btn_delete {$btn_cls}" onclick="{$this->tableId}_{$this->type}_delete_function(this)">
                    {$icon_span}{$title}
                </button>
            {{# }}}

EOT;

            $this->script .= <<<EOT
            <script>
                function {$this->tableId}_{$this->type}_delete_function(that){
                    var ids = [];
                    if('{$this->type}'=='toolbar'){
                        var data = layui.{$this->tableType}.checkStatus('{$this->tableId}').data;
                        data.map(item=>{
                            ids.push(item['{$this->pk}'])
                        });
                    }else{
                        ids.push($(that).attr('row-id'));
                    }
                    if(ids.length==0){
                        layer.msg('请选择要操作的项！',{
                            icon:5,
                            time:2000,
                            shade:[0.6,'#000',false]
                        });
                        return false;
                    }

                    var noDeletePrimarykeys = {$noDeletePrimarykeys};
                    var is_exit = false;
                    if(noDeletePrimarykeys.length>0){
                        ids.map(item=>{
                            if(noDeletePrimarykeys.includes(item) || noDeletePrimarykeys.includes(item.toString())){
                                console.log(noDeletePrimarykeys.includes(item));
                                layer.msg('当前行不允许{$title}！',{
                                    icon:5,
                                    time:2000,
                                    shade:[0.6,'#000',false]
                                });
                                is_exit = true;
                            }
                        });
                    }

                    if(!is_exit){
                        layer.confirm('是否确认{$title}？', {
                            btn: ['确定', '取消'],
                            icon:'doubt'
                        }, function(index, layero){
                            //确认按钮回调
                            layer.close(index);
                            window.loading  = layer.load(2, { shade:  [0.2, '#000'] });
                            $.post('{$href}',{{$this->pk}:ids.join(",")},function(res){
                                layer.close(window.loading);
                                if(res.code==1){
                                    layer.msg(res.msg,{
                                        icon:6,
                                        time:2000,
                                        shade:[0.6,'#000',false]
                                    });
                                    layui.{$this->tableType}.reloadData('{$this->tableId}');
                                }else{
                                    layer.msg(res.hasOwnProperty('msg') && res.msg?res.msg:'操作失败！',{
                                        icon:5,
                                        time:2000,
                                        shade:[0.6,'#000',false]
                                    });
                                }
                            });
                        });
                    }
                }
           </script>
EOT;
            $this->html .= $html;
        }
        return $this;
    }

    /**
     * @param boolean $show   是否显示刷新按钮
     * @param string  $title  按钮文字
     */
    public function refreshBtn($show = true, $title = null)
    {
        if ($show == true && $this->type == 'toolbar') {
            if ($title === null) {
                $title = $this->parent->refreshText;
            }
            $noDeletePrimarykeys = json_encode($this->parent->noDeletePrimarykeys);

            $html = <<<EOT

                <button type="button" class="julyadmin_{$this->tableId}_{$this->type}_btn_refresh
                btn btn-sm btn-info" onclick="{$this->tableId}_{$this->type}_refresh_function(this)">
                    <span class="mdi mdi-refresh" aria-hidden="true"></span>{$title}
                </button>

EOT;

            $this->html .= $html;

            $this->script .= <<<EOT

            <script>
                function {$this->tableId}_{$this->type}_refresh_function(that){
                    layui.{$this->tableType}.reloadData('{$this->tableId}',{where:layui.table.getOptions('{$this->tableId}').where});
                }
            </script>

EOT;
        }
        return $this;
    }

    /**
     * 创建链接按钮
     * @param string $action        方法
     * @param string $title         按钮title
     * @param string $function      js方法
     * @param string $icon          图标样式
     * @param string $class         按钮class
     */
    public function linkBtn($action = '', $title = null, $function = '', $icon = '', $class = '')
    {
        if (!$action) {
            throw new \Exception("参数\$action不能为空！");
        }
        $preg = "/^[a-zA-Z\d]*$/i";
        if (!preg_match($preg, $action)) {
            throw new \Exception("参数\$action只能为大小写字母和数字组合！");
        }
        if ($this->type == 'tablerow') {
            $icon_span = '';
        } else {
            $icon_span = '<span class="' . $icon . '" aria-hidden="true"></span>';
        }

        if (!AdminRoleLogic::isHaveButtonPermission($this->module, request()->controller(), $action)) {
            return $this;
        }

        if ($this->type == 'tablerow') {
            $btn_cls = 'layui-btn layui-btn-xs';
        } else {
            $btn_cls = 'btn btn-sm';
        }

        $html = <<<EOT

            {{# if(!d.hasOwnProperty('__{$action}_hidden__') || d.__{$action}_hidden__==false){}}
            <button row-id="{{d.{$this->pk}}}" type="button" id="julyadmin_{$this->type}_{$action}"
            class="julyadmin_{$this->tableId}_{$this->type}_linkbtn_{$action} {$btn_cls} {$class}"
            onclick="{$function}">
                {$icon_span}{$title}
            </button>
            {{# }}}

EOT;
        $this->html .= $html;
        return $this;
    }

    /**
     * 创建打开窗口按钮
     * @param string  $action          方法
     * @param string  $title           按钮title
     * @param string  $href            按钮链接
     * @param string  $icon            图标样式
     * @param string  $class           按钮class
     * @param string  $window_width    窗口宽度
     * @param string  $window_height   窗口高度
     * @param boolean $is_parent_open  是否从父窗口打开
     */
    public function openWindowBtn($action = '', $title = null, $href = '', $icon = '', $class = '', $window_width = '90%', $window_height = '90%', $is_parent_open = false)
    {
        if (!$action) {
            throw new \Exception("参数\$action不能为空！");
        }

        $preg = "/^[a-zA-Z\d]*$/i";
        if (!preg_match($preg, $action)) {
            throw new \Exception("参数\$action只能为大小写字母和数字组合！");
        }
        if ($this->type == 'tablerow') {
            $icon_span = '';
        } else {
            $icon_span = '<span class="' . $icon . '" aria-hidden="true"></span>';
        }

        if ($this->type == 'tablerow') {
            $btn_cls = 'layui-btn layui-btn-xs';
        } else {
            $btn_cls = 'btn btn-sm';
        }

        if (!AdminRoleLogic::isHaveButtonPermission($this->module, request()->controller(), $action)) {
            return $this;
        }

        $parent = $is_parent_open ? 'parent.' : '';
        $html   = <<<EOT

                {{# if(!d.hasOwnProperty('__{$action}_hidden__') || d.__{$action}_hidden__==false){}}
                <button row-id="{{d.{$this->pk}}}" href="{$href}" id="julyadmin_{$this->type}_{$action}" type="button" class="julyadmin_{$this->tableId}_{$this->type}_{$action} {$btn_cls} {$class}" onclick="{$this->tableId}_{$this->type}_{$action}_open_window_function(this)">
                   {$icon_span}{$title}
               </button>
               {{# }}}

EOT;
        $this->script .= <<<EOT

                <script>
                    function {$this->tableId}_{$this->type}_{$action}_open_window_function(that){
                        var url = '{$href}';
                        var ids = [];
                        if('{$this->type}'=='toolbar'){
                            var data = layui.{$this->tableType}.checkStatus('{$this->tableId}').data;
                            data.map(item=>{
                                ids.push(item['{$this->pk}'])
                            });
                        }else{
                            ids.push($(that).attr('row-id'));
                        }
                        if(ids.length>0){
                            if(url.indexOf("?")>-1){
                                url = url+'&{$this->pk}='+ids.join(",");
                            }else{
                                url = url+'?{$this->pk}='+ids.join(",");
                            }
                        }
                        {$parent}layer.open({
                            type: 2,
                            title: '{$title}',
                            shadeClose: false,
                            shade:0.5,
                            maxmin: true, //开启最大化最小化按钮
                            area: ['{$window_width}', '{$window_height}'],
                            content: url
                        });
                    }
               </script>

EOT;
        $this->html .= $html;
        return $this;
    }

    /**
     * 换行
     * @Author   July
     * @DateTime 2025-02-25T17:02:44+0800
     * @return   string    换行
     */
    public function br()
    {
        $this->html .= '<br>';
        return $this;
    }

    /**
     * 向后插入html
     * @param string $html  html内容
     */
    public function afterHtml($html = '')
    {
        $this->html .= $html;
        return $this;
    }

    /**
     * 向前插入html
     * @param string $html  html内容
     */
    public function beforeHtml($html = '')
    {
        $this->html = $html . $this->html;
        return $this;
    }

    /**
     * 绑定表格id
     * @param string $tableId  表格id，自己定义
     */
    public function bindTableId($tableId = '')
    {
        $this->tableId = $tableId;
        return $this;
    }

    /**
     * 添加script代码
     * @Author
     * @DateTime 2023-05-27T12:40:41+0800
     * @param    string                   $script js代码
     */
    public function addScript($script = '')
    {
        $this->script .= $script;
        return $this;
    }

    /**
     * 渲染工具栏
     */
    public function render()
    {
        if ($this->type == 'tablerow') {
            $this->html = str_replace("\r\n", "", $this->html);
        }
        return ['html' => $this->html, 'script' => $this->script];
    }
}
